<?php
namespace App\HttpController\Pudu;

use App\Common\Controller\Rest;

class Products extends Rest
{
    public $modelName = 'Product'; // model 类名称

    public function GETIndex()
    {
        // TODO 判断当前用户身份  会员只能兑换积分商品 店铺只能帮助会员兑换电子币商品
        $roleId = $this->model('Member')->where(['id' => $this->param['userId']])->value('roleId');

        // TODO 推荐账户列表
        switch ($roleId) {
            case 1:
                $this->param['type'] = 1; // 只能查看本店铺所属的会员
                break;
            case 2:
                // TODO 市代理  可查看下属店铺 和  下属区县
                $this->param['type'] = 2; // 只能查看本店铺所属的会员
                break;
            default:
                break;
        }
        if (isset($this->param['Id'])) {
            $res = $this->model()->getDataById($this->param['Id']);
        } else {
            $res = $this->model()->getDataList($this->param);
        }
        $this->result($res, ['msg' => self::$model->getError(), 'data' => $res]);
    }

    public function DELETEIndex()
    {
        // TODO 检查是否已经生成订单
        $this->checkOrders([$this->param['Id']]);
        $res = $this->model()->delDataById($this->param['Id']);
        $this->result($res, ['msg' => self::$model->getError()]);
    }

    public function POSTDeletes()
    {
        // TODO 检查是否已经生成订单
        $this->checkOrders($this->param['ids']);
        $res = $this->model()->delDatas($this->param['ids']);
        $this->result($res, ['msg' => self::$model->getError()]);
    }

    private function checkOrders($productId)
    {
        $res = $this->model('Order')->where('productId', 'in', $productId)->count();
        $this->abort(!$res, ['msg' => '商品已经生成订单, 不可删除!']);
    }
}
